package demo;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class TopicReceiver2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.建立连接
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");

        Connection connection = factory.newConnection();
        //2.建立通道
        Channel channel = connection.createChannel();

        //3.接收消息
        //创建交换机
        channel.exchangeDeclare("topic_exchange",BuiltinExchangeType.TOPIC);
        //创建队列
        channel.queueDeclare("topic_queue2",false,false,false,null);
        // 绑定队列到交换机
        channel.queueBind("topic_queue2", "topic_exchange", "#");

        //创建一个消费者
        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String str=new String(body);
                System.out.println("topicReceiver2收到消息："+str);
            }
        };
        //消费
        channel.basicConsume("topic_queue2",true,consumer);

    }
}
